package com.ricohgag.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ricohgag.entity.News;
import com.ricohgag.entity.NewsCatalog;
import com.ricohgag.mapper.NewsCatalogMapper;
import com.ricohgag.mapper.NewsMapper;
import com.ricohgag.service.NewsService;
import org.junit.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 肖晖
 * @since 2018-08-25
 */
@Service
public class NewsServiceImpl extends ServiceImpl<NewsMapper, News> implements NewsService {
    @Autowired
    private NewsMapper newsMapper;
    @Autowired
    private NewsCatalogMapper newsCatalogMapper;

    @Override
    public IPage<News> selectNewsPage(String name, Integer cId, Page<News> page) throws Exception{
        QueryWrapper<News> qw = new QueryWrapper<>();
        //根据标题查询
        if(name != null){
            qw.like("news_title", name);
        }

        System.out.println("cId: "+cId);

        //点击了分类查询
        if(cId != 0){
            NewsCatalog newsCatalog = newsCatalogMapper.selectById(cId);
            //顶级分类则显示所有子分类
            if(newsCatalog.getCatalogId()==0){
                List<NewsCatalog> newsCatalogs = newsCatalogMapper.selectList(new QueryWrapper<NewsCatalog>().eq("catalog_id", newsCatalog.getId()));

                //循环的增加子分类的查询条件
                for(NewsCatalog catalog:newsCatalogs) {
                    qw.eq("catalog_id", catalog.getId());
                    qw.or();
                }

            }
            qw.eq("catalog_id", cId);

        }

        IPage<News> shopAdIPage = newsMapper.selectPage(page, qw);
        Assert.assertSame(page, shopAdIPage);
        System.err.println("fuck: "+shopAdIPage.getRecords());
        return shopAdIPage;
    }

    @Override
    public News seleNewsOne(Integer id) throws Exception{

        return newsMapper.selectById(id);
    }

    @Override
    public int updateNews(News news) throws Exception{
        return newsMapper.updateById(news);
    }

    @Override
    public int insertNews(News news) throws Exception{
        return newsMapper.insert(news);
    }

    @Override
    public int deleteNews(int id) throws Exception{
        return newsMapper.deleteById(id);
    }
}
